package com.woniuxy.order.controller;

import com.woniuxy.order.dto.OrderApplicationDto;
import com.woniuxy.order.dto.OrderApprovalDto;
import com.woniuxy.order.dto.OrderProcessDto;
import com.woniuxy.order.entity.OrderApplication;
import com.woniuxy.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单管理Controller
 */
@Slf4j
@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建订单申请
     */
    @PostMapping
    public ResponseEntity<OrderApplication> createOrderApplication(
            @Valid @RequestBody OrderApplicationDto orderApplicationDto,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {
        
        log.info("创建订单申请，用户：{}", currentUser);
        OrderApplication orderApplication = orderService.createOrderApplication(orderApplicationDto, currentUser);
        return ResponseEntity.ok(orderApplication);
    }
    
    /**
     * 更新订单申请
     */
    @PutMapping("/{orderId}")
    public ResponseEntity<OrderApplication> updateOrderApplication(
            @PathVariable Long orderId,
            @Valid @RequestBody OrderApplicationDto orderApplicationDto,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {
        
        log.info("更新订单申请，订单ID：{}，用户：{}", orderId, currentUser);
        OrderApplication orderApplication = orderService.updateOrderApplication(orderId, orderApplicationDto, currentUser);
        return ResponseEntity.ok(orderApplication);
    }
    
    /**
     * 删除订单申请
     */
    @DeleteMapping("/{orderId}")
    public ResponseEntity<Void> deleteOrderApplication(
            @PathVariable Long orderId,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "admin") String currentUser) {
        
        log.info("删除订单申请，订单ID：{}，用户：{}", orderId, currentUser);
        orderService.deleteOrderApplication(orderId, currentUser);
        return ResponseEntity.ok().build();
    }
    
    /**
     * 根据ID获取订单申请
     */
    @GetMapping("/{orderId}")
    public ResponseEntity<OrderApplication> getOrderApplicationById(@PathVariable Long orderId) {
        log.info("获取订单申请，订单ID：{}", orderId);
        OrderApplication orderApplication = orderService.getOrderApplicationById(orderId);
        return ResponseEntity.ok(orderApplication);
    }
    
    /**
     * 根据订单编号获取订单申请
     */
    @GetMapping("/orderNo/{orderNo}")
    public ResponseEntity<OrderApplication> getOrderApplicationByOrderNo(@PathVariable String orderNo) {
        log.info("获取订单申请，订单编号：{}", orderNo);
        OrderApplication orderApplication = orderService.getOrderApplicationByOrderNo(orderNo);
        return ResponseEntity.ok(orderApplication);
    }
    
    /**
     * 分页查询订单申请
     */
    @GetMapping
    public ResponseEntity<Page<OrderApplication>> getOrderApplications(
            Pageable pageable,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String applicationStatus,
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "system") String currentUser) {
        
        log.info("分页查询订单申请，用户：{}", currentUser);
        Page<OrderApplication> orders = orderService.getOrderApplications(pageable, customerName, applicationStatus, currentUser);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 获取用户的订单申请列表
     */
    @GetMapping("/user")
    public ResponseEntity<List<OrderApplication>> getUserOrderApplications(
            @RequestHeader("X-User-Name") String currentUser) {
        
        log.info("获取用户订单申请列表，用户：{}", currentUser);
        List<OrderApplication> orders = orderService.getUserOrderApplications(currentUser);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 获取待审批订单列表
     */
    @GetMapping("/pending")
    public ResponseEntity<List<OrderApplication>> getPendingOrderApplications(
            @RequestHeader("X-User-Name") String currentUser) {
        
        log.info("获取待审批订单列表，用户：{}", currentUser);
        List<OrderApplication> orders = orderService.getPendingOrderApplications(currentUser);
        return ResponseEntity.ok(orders);
    }
    
    /**
     * 提交订单申请（启动工作流）
     */
    @PostMapping("/{orderId}/submit")
    public ResponseEntity<Map<String, String>> submitOrderApplication(
            @PathVariable Long orderId,
            @RequestHeader("X-User-Name") String currentUser) {
        
        log.info("提交订单申请，订单ID：{}，用户：{}", orderId, currentUser);
        String processInstanceId = orderService.submitOrderApplication(orderId, currentUser);
        
        Map<String, String> result = new HashMap<>();
        result.put("processInstanceId", processInstanceId);
        result.put("message", "订单申请提交成功，已启动审批流程");
        return ResponseEntity.ok(result);
    }
    
    /**
     * 审批订单
     */
    @PostMapping("/approve")
    public ResponseEntity<Map<String, String>> approveOrder(
            @Valid @RequestBody OrderApprovalDto approvalDto,
            @RequestHeader("X-User-Name") String currentUser) {
        
        log.info("审批订单，订单ID：{}，审批结果：{}，用户：{}", 
            approvalDto.getOrderId(), approvalDto.getApprovalResult(), currentUser);
        
        orderService.approveOrder(approvalDto, currentUser);
        
        Map<String, String> result = new HashMap<>();
        result.put("message", "审批操作完成");
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取订单流程信息
     */
    @GetMapping("/{orderId}/process")
    public ResponseEntity<OrderProcessDto> getOrderProcess(@PathVariable Long orderId) {
        log.info("获取订单流程信息，订单ID：{}", orderId);
        OrderProcessDto processDto = orderService.getOrderProcess(orderId);
        return ResponseEntity.ok(processDto);
    }
    
    /**
     * 获取订单流程步骤
     */
    @GetMapping("/process/{processInstanceId}/steps")
    public ResponseEntity<List<OrderProcessDto.ProcessStepDto>> getOrderProcessSteps(
            @PathVariable String processInstanceId) {
        
        log.info("获取订单流程步骤，流程实例ID：{}", processInstanceId);
        List<OrderProcessDto.ProcessStepDto> steps = orderService.getOrderProcessSteps(processInstanceId);
        return ResponseEntity.ok(steps);
    }
    
    /**
     * 获取订单统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getOrderStatistics(
            @RequestHeader(value = "X-User-Name", required = false, defaultValue = "system") String currentUser) {
        
        log.info("获取订单统计信息，用户：{}", currentUser);
        Map<String, Object> statistics = orderService.getOrderStatistics(currentUser);
        return ResponseEntity.ok(statistics);
    }
    
    /**
     * 取消订单申请
     */
    @PostMapping("/{orderId}/cancel")
    public ResponseEntity<Map<String, String>> cancelOrderApplication(
            @PathVariable Long orderId,
            @RequestParam String reason,
            @RequestHeader("X-User-Name") String currentUser) {
        
        log.info("取消订单申请，订单ID：{}，原因：{}，用户：{}", orderId, reason, currentUser);
        orderService.cancelOrderApplication(orderId, reason, currentUser);
        
        Map<String, String> result = new HashMap<>();
        result.put("message", "订单申请已取消");
        return ResponseEntity.ok(result);
    }
}
